//
//  ZZMusicStyleVC.m
//  ZZBlue
//
//  Created by stonesMonkey on 2017/10/3.
//  Copyright © 2017年 stonesMonkey. All rights reserved.
//

#import "ZZMusicStyleVC.h"

#define kZZMusicStyleIndetier @"ZZMusicStyleIndetier"
#import "ZZLightViewSettingCollectionViewCell.h"
#import "ZZLightViewSettingCVCellModel.h"
#import "ZZMusicLightTool.h"
#import "ZZMusicMoreLightTool.h"

@interface ZZMusicStyleVC ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong)ZZLightViewCellModel *changeModel;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (weak, nonatomic) IBOutlet UISlider *pinLvSlider;
// 中间那个圆点击的View
@property (weak, nonatomic) IBOutlet ZZView *touView;

@property (weak, nonatomic) IBOutlet UIButton *selectColorBtn;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flow;

@property (weak, nonatomic) IBOutlet UIButton *deleteBtn;

@property (nonatomic, strong)ZZLightViewSettingCVCellModel *currentSelectModel;

@property (nonatomic, strong)NSMutableArray<ZZLightViewSettingCVCellModel *> *collectionViewModels;

@end

@implementation ZZMusicStyleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = @"选择颜色的样式";
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = [UIColor whiteColor];
    [titleLabel sizeToFit];
    self.navigationItem.titleView = titleLabel;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"icon_fanh"] forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(0, 0, 16, 16);
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(saveBtnDidClick) forControlEvents:UIControlEventTouchDown];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    [rightBtn setTitleColor:[UIColor zColorWithHex:0xF8D11C] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    [self setupSubView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(btn2Move:)];
    
    [self.selectColorBtn addGestureRecognizer:pan];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Func
- (void)setupSubView {
    
    self.selectColorBtn.frame = CGRectMake(60, 60, 32, 32);
    self.selectColorBtn.layer.cornerRadius = 16;
    self.selectColorBtn.layer.masksToBounds = YES;
    self.selectColorBtn.layer.borderWidth = 3;
    self.selectColorBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    
    self.flow.itemSize = CGSizeMake(60, 45);
    self.flow.minimumInteritemSpacing = 4;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZZLightViewSettingCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kZZMusicStyleIndetier];
    self.collectionView.backgroundColor = [UIColor blackColor];
    
    [self setSliderView:self.pinLvSlider];
    [self.pinLvSlider addTarget:self action:@selector(tuoweiSliderChange) forControlEvents:UIControlEventValueChanged];
    
    self.deleteBtn.layer.cornerRadius = 12.5;
    self.deleteBtn.layer.borderWidth = 1;
    self.deleteBtn.layer.borderColor = [UIColor zColorWithRed:102 green:102 blue:102].CGColor;
    self.deleteBtn.layer.masksToBounds = YES;
    
    self.touView.viewDidClick = ^(UIColor *color,CGPoint location) {
        
        if (self.currentSelectModel == nil) {
            
            return ;
        }
        
        self.currentSelectModel.color = color;
        
        NSInteger index = [self.collectionViewModels indexOfObject:self.currentSelectModel];
        ZZColorRGBA *rgba = self.changeModel.colors[index];
        NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
        rgba.R = [rgbaArr[0] floatValue];
        rgba.G = [rgbaArr[1] floatValue];
        rgba.B = [rgbaArr[2] floatValue];
        
        
        self.selectColorBtn.center = location;
        [self.changeModel reloadImage];
        
        [self.collectionView reloadData];
    };

    
}

- (void)setSliderView:(UISlider *)slider {
    
    slider.backgroundColor = [UIColor zColorWithHex:0x34373b];
    slider.minimumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.maximumTrackTintColor =  [UIColor zColorWithHex:0x34373b];
    slider.layer.cornerRadius = 8;
    [slider setThumbImage:[UIImage imageNamed:@"icon_huaik"] forState:UIControlStateNormal];
}

#pragma mark - action
- (void)back {
    
    if ([self.model isEqualModel:self.changeModel]) {
        
        
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"尚未保存修改，你需要保存？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"不保存" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [self.navigationController popViewControllerAnimated:YES];
                                                              }];
        
        [alert addAction:defaultAction];
        
        UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * action) {
                                                               
                                                               [self.model equalToModel:self.changeModel];
                                                               // 保存并推出
                                                               if(self.updateData) {
                                                                   
                                                                   self.updateData(self.model);
                                                               }
                                                               
                                                               [self.navigationController popViewControllerAnimated:YES];
                                                           }];
        
        [alert addAction:sureAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
    
}

- (void)saveBtnDidClick {
    
    if ([self.model isEqualModel:self.changeModel]) {
        
        
        NSLog(@"什么都不用做");
    } else {
        
        [self.model equalToModel:self.changeModel];
        // 保存并推出
        if(self.updateData) {
            
           
            
            
            
            self.updateData(self.model);
        }
        
    }
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (IBAction)changeNameBtnClick:(id)sender {
    
    UIAlertController* alertVc = [UIAlertController alertControllerWithTitle:@"修改名称"
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];
    
    __block UITextField *nameTextFIeld = nil;
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        nameTextFIeld = textField;
    }];
    
    
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                          handler:^(UIAlertAction * action) {}];
    
    UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           
                                                           if (nameTextFIeld.text.length == 0) {
                                                               
                                                               return ;
                                                           }
                                                           self.nameLabel.text = nameTextFIeld.text;
                                                           self.changeModel.title = nameTextFIeld.text;
                                                       }];
    [alertVc addAction:defaultAction];
    [alertVc addAction:sureAction];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (IBAction)suiJiBtnClick:(UIButton *)sender {
}

- (IBAction)listBtnClick:(UIButton *)sender {

}

#pragma mark - 设置频率输出
- (void)tuoweiSliderChange {
    
    self.changeModel.pinLv = self.pinLvSlider.value;
}


#pragma mark - collectionView D &D
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.collectionViewModels.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZLightViewSettingCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kZZMusicStyleIndetier forIndexPath:indexPath];
    if(self.collectionViewModels.count == indexPath.row) {
        
        ZZLightViewSettingCVCellModel *model = [ZZLightViewSettingCVCellModel new];
        
        model.isSelect = NO;
        model.model =  ZZLightViewSettingCVCellStyleAdd;
        
        cell.model = model;
    } else {
        
        cell.model = self.collectionViewModels[indexPath.row];
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.collectionViewModels.count == indexPath.row) {
        
        self.currentSelectModel.isSelect = NO;
        self.currentSelectModel = nil;
        
        ZZLightViewSettingCVCellModel*model2 = [ZZLightViewSettingCVCellModel new];
        model2.model = ZZLightViewSettingCVCellStyleSelect;
        model2.color = [UIColor redColor];
        
        [self.collectionViewModels addObject:model2];
        [self.collectionView reloadData];
        [self.changeModel.colors addObject: [ZZColorRGBA colorRGBAWithR:255.0 G:0 B:0 A:1]];
        
        [self.changeModel reloadImage];
        
    } else {
        
        self.currentSelectModel.isSelect = NO;
        ZZLightViewSettingCVCellModel *model = self.collectionViewModels[indexPath.row];
        model.isSelect = YES;
        self.currentSelectModel = model;
        
        [self.collectionView reloadData];
        
        
        
    }
}


#pragma mark - set & get

- (void)setModel:(ZZLightViewCellModel *)model {
    
    _model = model;
    [self setChangeModelForModel:model];
    
}

- (void)setChangeModelForModel:(ZZLightViewCellModel *)model {
    
    ZZLightViewCellModel *changeModel = [ZZLightViewCellModel new];
    changeModel.colors = [NSMutableArray arrayWithArray:model.colors];
    changeModel.isAnticlockwise = model.isAnticlockwise;
    changeModel.colorNumber = model.colorNumber;
    changeModel.tuoWeiLength = model.tuoWeiLength;
    changeModel.pinLv = model.pinLv;
    changeModel.lightValue = model.lightValue;
    changeModel.colorZuHeShu = model.colorZuHeShu;
    changeModel.imageSize = model.imageSize;
    changeModel.imagePath = model.imagePath;
    changeModel.model = model.model == LightModelAdd? LightModelFugai: model.model;
    changeModel.title = model.title;
    
    for (NSInteger index = 0; index < changeModel.colorZuHeShu; index++) {
        
        NSMutableArray *mtbArr = model.colorsGroup[index];
        NSMutableArray *newMtbArr = [NSMutableArray array];
        for (ZZColorRGBA *rgba in mtbArr) {
            
            [newMtbArr addObject:[rgba copy]];
        }
        [changeModel.colorsGroup addObject:newMtbArr];
    }
    
    self.changeModel = changeModel;
    
    
}

- (void)setChangeModel:(ZZLightViewCellModel *)changeModel {
    
    _changeModel = changeModel;
    
    self.nameLabel.text = changeModel.title;
    self.pinLvSlider.value = changeModel.pinLv;
    
    [self.collectionViewModels removeAllObjects];
    for (ZZColorRGBA *rgb in changeModel.colors) {
        
        ZZLightViewSettingCVCellModel *model = [ZZLightViewSettingCVCellModel new];
        model.color = [rgb color];
        model.isSelect = NO;
        model.model =  ZZLightViewSettingCVCellStyleSelect;
        [self.collectionViewModels addObject:model];
    }
    [self.collectionView reloadData];
}

- (NSMutableArray<ZZLightViewSettingCVCellModel *> *)collectionViewModels {
    
    if (!_collectionViewModels) {
        
        _collectionViewModels = [NSMutableArray array];
    }
    return _collectionViewModels;
}

#pragma mark - <#name#>
- (void)btn2Move:(UIPanGestureRecognizer *)pan {
    
    CGPoint  point = [pan translationInView:self.touView];
    CGFloat width = self.touView.frame.size.width - self.selectColorBtn.frame.size.width / 2;
    
    CGRect originalFrame = self.selectColorBtn.frame;
    
    originalFrame.origin.x += point.x;
    originalFrame.origin.y += point.y;
    
    // 圆心
    CGPoint center = CGPointMake(CGRectGetMidX(originalFrame) - width / 2,CGRectGetMidY(originalFrame) - width /2);
    
    CGFloat offetX  = self.selectColorBtn.frame.size.width / 2;
    CGFloat offerY = self.selectColorBtn.frame.size.height / 2;
    if (center.x > 0) {
        
        offetX = offetX / 2;
    }
    if(center.y > 0) {
        
        offerY = offerY / 2;
    }
    
    CGFloat x2 = fabs(center.x - offetX ) * fabs(center.x - offetX);
    CGFloat y2 = fabs(center.y - offerY)  * fabs(center.y  - offerY) ;
    CGFloat length = sqrt(x2 + y2);
    if (length >= width / 2) {
        
        originalFrame = self.selectColorBtn.frame;
    }
    
    self.selectColorBtn.frame = originalFrame;
    [pan setTranslation:CGPointZero inView:self.touView];
    
    switch (pan.state) {
        case UIGestureRecognizerStateChanged:
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            // 输出当前ImageView上的颜色值
            UIColor*color = [self colorOfPoint:self.selectColorBtn.center];
            
            if (self.currentSelectModel) {
                
                self.currentSelectModel.color = color;
                [self.collectionView reloadData];
                NSInteger index = [self.collectionViewModels indexOfObject:self.currentSelectModel];
                ZZColorRGBA *rgba = self.changeModel.colors[index];
                NSArray *rgbaArr =[ZZCircleTool colorForGGB:color];
                rgba.R = [rgbaArr[0] floatValue];
                rgba.G = [rgbaArr[1] floatValue];
                rgba.B = [rgbaArr[2] floatValue];
                
                [self.changeModel reloadImage];
                // 改变index颜色
                
#pragma 这里就可以输出颜色了
                
            }
#pragma mark - 颜色输出
            NSLog(@"%@",color);
        }
            break;
            
        default:
            break;
    }
}

- (UIColor *)colorOfPoint:(CGPoint)point {
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);
    
    CGContextTranslateCTM(context, -point.x, -point.y);
    
    [self.touView.layer renderInContext:context];
    
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];
    
    return color;
}

- (IBAction)deleteColor:(UIButton *)sender {
    
    if (self.collectionViewModels.count >1 && self.currentSelectModel.isSelect == YES) {
        
        [self.changeModel.colors removeObjectAtIndex:[self.collectionViewModels indexOfObject:self.currentSelectModel]];
        [self.collectionViewModels removeObject:self.currentSelectModel];
        
        self.currentSelectModel = nil;
        
        [self.collectionView reloadData];
        [self.changeModel reloadImage];
    }
    
}


@end
